import { defineStore } from 'pinia'
import { adminApi } from '@/api/admin'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: (() => {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        // 检查是否为 null、空字符串或 "undefined" 字符串
        if (!userInfoStr || userInfoStr === 'null' || userInfoStr === 'undefined') {
          return null
        }
        return JSON.parse(userInfoStr)
      } catch (error) {
        console.warn('解析 userInfo 失败:', error)
        // 清除无效数据
        localStorage.removeItem('userInfo')
        return null
      }
    })()
  }),

  getters: {
    isLogin: (state) => !!state.token
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const data = await adminApi.login(loginForm)
        
        // 后端返回的字段是 token，不是 access_token
        this.token = data.token
        // 后端返回的用户信息不在 user 对象中，而是直接在 data 中
        this.userInfo = {
          userId: data.userId,
          role: data.role,
          nickname: data.nickname,
          avatar: data.avatar,
          roles: data.roles || [] // 角色列表，用于权限控制
        }
        
        localStorage.setItem('token', this.token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        
        return true
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
  }
})

